package com.dormitory.ui;

import com.dormitory.model.Student;
import com.dormitory.service.StudentService;
import com.dormitory.service.impl.StudentServiceImpl;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class StudentPanel extends JPanel {
    private StudentService studentService;
    private JTable studentTable;
    private DefaultTableModel tableModel;
    private JTextField searchField;
    private JComboBox<String> genderComboBox;
    private JTextField nameField;
    private JTextField majorField;
    private JTextField classField;
    private JTextField phoneField;
    private JTextField yearField;
    private JPanel resultStatsPanel;

    public StudentPanel() {
        studentService = new StudentServiceImpl();
        initUI();
        loadStudentData();
    }

    private void initUI() {
        setLayout(new BorderLayout());
        // 工具栏
        JToolBar toolBar = createToolBar();
        add(toolBar, BorderLayout.NORTH);
        
        // 创建结果统计面板
        resultStatsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        resultStatsPanel.setBorder(BorderFactory.createTitledBorder("搜索结果统计"));
        add(resultStatsPanel, BorderLayout.SOUTH);
        
        // 表格
        createTable();
        JScrollPane scrollPane = new JScrollPane(studentTable);
        add(scrollPane, BorderLayout.CENTER);
    }

    private JToolBar createToolBar() {
        JToolBar toolBar = new JToolBar();
        toolBar.setFloatable(false);

        // 搜索框
        searchField = new JTextField(20);
        JButton searchButton = new JButton("搜索");
        searchButton.addActionListener(e -> searchStudents());

        // 添加按钮
        JButton addButton = new JButton("添加");
        addButton.addActionListener(e -> showAddDialog());

        // 修改按钮
        JButton editButton = new JButton("修改");
        editButton.addActionListener(e -> showEditDialog());

        // 删除按钮
        JButton deleteButton = new JButton("删除");
        deleteButton.addActionListener(e -> deleteStudent());

        toolBar.add(new JLabel("搜索："));
        toolBar.add(searchField);
        toolBar.add(searchButton);
        toolBar.addSeparator();
        toolBar.add(addButton);
        toolBar.add(editButton);
        toolBar.add(deleteButton);

        return toolBar;
    }

    private void createTable() {
        String[] columnNames = {"学号", "姓名", "性别", "专业", "班级", "联系电话", "入学年份"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        studentTable = new JTable(tableModel);
        studentTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    private void loadStudentData() {
        tableModel.setRowCount(0);
        List<Student> students = studentService.getAllStudents();
        for (Student student : students) {
            addStudentToTable(student);
        }
        // 显示全部数据的统计信息
        updateSearchStats(students, "");
    }

    private void addStudentToTable(Student student) {
        Object[] rowData = {
            student.getStudentId(),
            student.getStudentName(),
            student.getGender(),
            student.getMajor(),
            student.getClassName(),
            student.getContactPhone(),
            student.getEnrollmentYear()
        };
        tableModel.addRow(rowData);
    }

    private void searchStudents() {
        String condition = searchField.getText().trim();
        tableModel.setRowCount(0);
        List<Student> students = studentService.searchStudents(condition);
        
        // 更新表格数据
        for (Student student : students) {
            addStudentToTable(student);
        }
        
        // 更新统计信息
        updateSearchStats(students, condition);
    }

    private void updateSearchStats(List<Student> students, String searchCondition) {
        resultStatsPanel.removeAll();
        
        // 创建统计信息标签
        JLabel totalLabel = new JLabel(String.format("总记录数: %d", students.size()));
        JLabel searchLabel = new JLabel(String.format("搜索条件: %s", searchCondition.isEmpty() ? "全部" : searchCondition));
        
        // 按性别统计
        long maleCount = students.stream().filter(s -> "男".equals(s.getGender())).count();
        long femaleCount = students.stream().filter(s -> "女".equals(s.getGender())).count();
        JLabel genderLabel = new JLabel(String.format("性别分布: 男(%d) 女(%d)", maleCount, femaleCount));
        
        // 按专业统计
        Map<String, Long> majorStats = students.stream()
            .collect(Collectors.groupingBy(Student::getMajor, Collectors.counting()));
        JLabel majorLabel = new JLabel("专业分布: " + 
            majorStats.entrySet().stream()
                .map(e -> String.format("%s(%d)", e.getKey(), e.getValue()))
                .collect(Collectors.joining(", ")));
        
        // 添加统计信息到面板
        resultStatsPanel.add(totalLabel);
        resultStatsPanel.add(new JLabel(" | "));
        resultStatsPanel.add(searchLabel);
        resultStatsPanel.add(new JLabel(" | "));
        resultStatsPanel.add(genderLabel);
        resultStatsPanel.add(new JLabel(" | "));
        resultStatsPanel.add(majorLabel);
        
        // 刷新面板
        resultStatsPanel.revalidate();
        resultStatsPanel.repaint();
    }

    private void showAddDialog() {
        StudentFormDialog dialog = new StudentFormDialog(SwingUtilities.getWindowAncestor(this), null);
        dialog.setVisible(true);
        if (dialog.isConfirmed()) {
            Student student = dialog.getStudent();
            if (studentService.addStudent(student)) {
                JOptionPane.showMessageDialog(this, "添加成功！");
                loadStudentData();
            } else {
                JOptionPane.showMessageDialog(this, "添加失败！");
            }
        }
    }

    private void showEditDialog() {
        int selectedRow = studentTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要修改的学生！");
            return;
        }
        Integer studentId = (Integer) tableModel.getValueAt(selectedRow, 0);
        Student student = studentService.getStudentById(studentId);
        if (student == null) {
            JOptionPane.showMessageDialog(this, "未找到学生信息！");
            return;
        }
        StudentFormDialog dialog = new StudentFormDialog(SwingUtilities.getWindowAncestor(this), student);
        dialog.setVisible(true);
        if (dialog.isConfirmed()) {
            Student updated = dialog.getStudent();
            updated.setStudentId(studentId);
            if (studentService.updateStudent(updated)) {
                JOptionPane.showMessageDialog(this, "修改成功！");
                loadStudentData();
            } else {
                JOptionPane.showMessageDialog(this, "修改失败！");
            }
        }
    }

    private void deleteStudent() {
        int selectedRow = studentTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要删除的学生！");
            return;
        }

        int confirm = JOptionPane.showConfirmDialog(this,
            "确定要删除这名学生吗？", "确认删除",
            JOptionPane.YES_NO_OPTION);
        
        if (confirm == JOptionPane.YES_OPTION) {
            Integer studentId = (Integer) tableModel.getValueAt(selectedRow, 0);
            if (studentService.deleteStudent(studentId)) {
                JOptionPane.showMessageDialog(this, "删除成功！");
                loadStudentData();
            } else {
                JOptionPane.showMessageDialog(this, "删除失败！");
            }
        }
    }
} 